package cn.lyvust.eais.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.lyvust.eais.common.bean.ResponseCode;
import cn.lyvust.eais.common.bean.ResponseResult;
import cn.lyvust.eais.common.exception.RequestException;
import cn.lyvust.eais.common.util.TreeUtil;
import cn.lyvust.eais.manage.dto.param.DictDistrictParam;
import cn.lyvust.eais.manage.entity.DictDistrictSub;
import cn.lyvust.eais.manage.service.DictDistrictSubService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 行政区划表 前端控制器
 * </p>
 *
 * @author ggzheng
 * @since 2021-01-24
 */
@Api(tags = {"省市地区"})
@RestController
@RequestMapping("/dict/district")
public class DictDistrictSubController {
    @Autowired
    private DictDistrictSubService dictDistrictSubService;

    @PostMapping(value = {"/list/pid"})
    @ApiOperation(value = "获取指定节点下的所有地区")
    public ResponseResult listByPid(@RequestBody DictDistrictParam param){
        String pid = param.getPid();
        if (StringUtils.isEmpty(pid)) {
            throw RequestException.fail("指定节点的ID不能为空!");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.likeLeft("parent_id", pid);
        List<DictDistrictSub> resList = dictDistrictSubService.list(wrapper);
        JSONArray result = TreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(resList)),"id","parentId","children");
        return ResponseResult.e(ResponseCode.OK, result);
    }
}
